package com.nexmo.hangman.dao.impl;

import com.nexmo.hangman.dao.GameDao;
import com.nexmo.hangman.dao.abs.AbstractDaoSupport;
import com.nexmo.hangman.domain.Game;
import org.hibernate.Criteria;
import org.hibernate.ScrollableResults;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class GameDaoImpl extends AbstractDaoSupport<Game, Long> implements GameDao{

    private final SessionFactory sessionFactory;

    @Autowired
    public GameDaoImpl(SessionFactory sessionFactory) {
        super(Game.class, sessionFactory);
        this.sessionFactory = sessionFactory;
    }

    @Override
    public Game getUserUnfinishedGame(Long userId) {
        return (Game) getUserActiveGamesCriteria(userId)
                .setMaxResults(1)
                    .uniqueResult();
    }

    @Override
    public void finishAllUserGames(Long userId) {

        ScrollableResults activeGames = getUserActiveGamesCriteria(userId).scroll();
        while ( activeGames.next() ) {
            Game activeGame = (Game)activeGames.get(0);
            activeGame.setFinished(true);
            saveOrUpdate(activeGame);
        }
    }

    @Override
    public List<Game> getAllActiveGames() {
        return getDefaultCriteria().add(Restrictions.eq("finished", false))
                .list();
    }

    private Criteria getUserActiveGamesCriteria(Long userId) {
        return getDefaultCriteria()
                .add(Restrictions.eq("user.id", userId))
                .add(Restrictions.eq("finished", false));
    }
}
